# !/usr/bin/python3
# -*- coding: utf-8 -*-

"""
租户信息表控制器类
----------------------------------------------------
@Project :   xinhou-openai-framework
@File    :   Tenant.py
@Contact :   sp_hrz@qq.com

@Modify Time      @Author    @Version    @Desciption
------------      -------    --------    -----------
2023/04/16 22:04  peng.shen   v1.0.0     None
"""

from fastapi import APIRouter, Depends
from fastapi.params import Path
from loguru import logger
from sqlalchemy.orm import Session

from apps.admin.schema.TenantSchema import ResTenantDetailSchema, ReqTenantFindSchema, \
    ReqTenantSaveSchema, ReqTenantUpdateSchema
from common.entity.Tenant import Tenant
from common.service.TenantService import TenantService
from xinhou_openai_framework.core.cache.CacheManager import CacheManager
from xinhou_openai_framework.core.db.DatabaseManager import DatabaseManager
from xinhou_openai_framework.core.exception.GlobalExceptionType import ParameterException
from xinhou_openai_framework.core.reponse.R import R
from xinhou_openai_framework.core.reponse.ResModel import ResModel
from xinhou_openai_framework.pages.PageHelper import PageResultHelper, PageHelper
from xinhou_openai_framework.utils.ObjDictUtil import ObjectDict

api = APIRouter()


@api.post('/admin/tenant/find',
          tags=["admin", "tenant"],
          response_model=ResModel[PageResultHelper[ResTenantDetailSchema]],
          summary="查询租户信息表信息带分页接口",
          description="通过参数模型传递条件查询")
async def find(search: PageHelper[ReqTenantFindSchema], db: Session = Depends(DatabaseManager().get_session)):
    logger.info("[find][request]:{}".format(search.model_dump()))
    return R.SUCCESS(TenantService(db).find_by(search))


@api.post('/admin/tenant/findAll',
          tags=["admin", "tenant"],
          response_model=ResModel[PageResultHelper[ResTenantDetailSchema]],
          summary="查询租户信息表信息接口",
          description="通过参数模型传递条件查询")
async def find_all(search: ReqTenantFindSchema, db: Session = Depends(DatabaseManager().get_session)):
    logger.info("[findAll][request]:{}".format(search.model_dump()))
    return R.SUCCESS(TenantService(db).find_all(search))


@api.post("/admin/tenant/save",
          tags=["admin", "tenant"],
          response_model=ResModel[ResTenantDetailSchema],
          summary="保存租户信息表信息接口",
          description="通过参数模型保存数据")
async def save(model: ReqTenantSaveSchema, db: Session = Depends(DatabaseManager().get_session)):
    logger.info("[save][request]:{}".format(model.model_dump_json()))
    return R.SUCCESS(TenantService(db).save(Tenant(**model.model_dump(exclude_unset=True))))


@api.get("/admin/tenant/delete/{id}",
         tags=["admin", "tenant"],
         response_model=ResModel,
         summary="删除租户信息表信息接口",
         description="根据ID删除数据")
async def delete(id: int = Path(title="ID不能为空"), db: Session = Depends(DatabaseManager().get_session)):
    logger.info("[detail][request]:{}".format({"id": id}))
    if id is None:
        raise ParameterException()
    return R.SUCCESS(TenantService(db).delete(Tenant(id=id)))


@api.post("/admin/tenant/update",
          tags=["admin", "tenant"],
          response_model=ResModel[ResTenantDetailSchema],
          summary="更新租户信息表信息接口",
          description="根据ID更新数据")
async def update(model: ReqTenantUpdateSchema, db: Session = Depends(DatabaseManager().get_session)):
    logger.info("[save][request]:{}".format(model.model_dump_json()))
    if model.id is None:
        raise ParameterException()
    return R.SUCCESS(TenantService(db).update(Tenant(**model.model_dump(exclude_unset=True))))


@api.get("/admin/tenant/detail/{id}",
         tags=["admin", "tenant"],
         response_model=ResModel[ResTenantDetailSchema],
         summary="获取租户信息表详情接口",
         description="根据ID获取数据")
async def detail(id: int = Path(title="ID不能为空"), db: Session = Depends(DatabaseManager().get_session)):
    logger.info("[detail][request]:{}".format({"id": id}))
    if id is None:
        raise ParameterException()
    return R.SUCCESS(TenantService(db).find_by_id(Tenant(id=id)))


@api.post("/admin/tenant/exists",
          tags=["admin", "tenant"],
          response_model=ResModel[bool],
          summary="判断租户数据是否存在接口",
          description="判断数据是否存在接口")
async def exists(model: ReqTenantFindSchema, db: Session = Depends(DatabaseManager().get_session)):
    logger.info("[detail][request]:{}".format(model.model_dump_json()))
    return R.SUCCESS(TenantService(db).exists(Tenant(**model.model_dump(exclude_unset=True))))


@api.post("/admin/tenant/cache",
          tags=["admin", "tenant"],
          response_model=ResModel[ResTenantDetailSchema],
          summary="查询租户缓存数据接口",
          description="查询租户缓存数据接口")
async def cache(model: ReqTenantFindSchema,
                cache_manager: CacheManager = Depends(CacheManager.get_instance)
                ):
    logger.info("[detail][request]:{}".format(model.model_dump_json()))
    tenant = ObjectDict(**cache_manager.get("tenant_1"))
    return R.SUCCESS(tenant)
